package com.hs.srm.admin.modules.quota.service.impl;


import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hs.srm.admin.modules.material.entity.MaterialEntity;
import com.hs.srm.admin.modules.material.service.MaterialService;
import com.hs.srm.admin.modules.quota.dao.QuotaDao;
import com.hs.srm.admin.modules.quota.entity.QuotaEntity;
import com.hs.srm.admin.modules.quota.entity.QuotaHistoryEntity;
import com.hs.srm.admin.modules.quota.service.QuotaHistoryService;
import com.hs.srm.admin.modules.quota.service.QuotaService;
import com.hs.srm.admin.modules.vendor.entity.VendorInfoEntity;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.DataFilter;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.common.utils.PageUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @author Sunnykid
 * @date 2019年3月17日
 */
@Service("quotaService")
public class QuotaServiceImpl extends ServiceImpl<QuotaDao, QuotaEntity> implements QuotaService {

    @Autowired
    QuotaDao quotaDao;

    @Autowired
    QuotaHistoryService quotaHistoryService;

    @Autowired
    private MaterialService materialService;

    @Autowired
    private VendorService vendorService;

    /**
     * 分页查询
     */
    @Override
    @DataFilter
    public PageUtils queryPage(Map<String, Object> params) {
        String vendorCode = (String) params.get("vendorCode");
        String materialCode = (String) params.get("materialCode");
        String werks = (String) params.get("werks");
        Page<QuotaEntity> page = this.selectPage(
                new QueryParam<QuotaEntity>(params).getPage(),
                new EntityWrapper<QuotaEntity>()
                        .eq(StringUtils.isNotBlank(vendorCode), "vendor_code", vendorCode)
                        .eq(StringUtils.isNotBlank(materialCode), "material_code", materialCode)
                        .eq(StringUtils.isNotBlank(werks), "werks", werks));
        return new PageUtils(page);
    }

    @Override
    public QuotaEntity findByNo(String materialCode, String vendorCode,
                                String werks) {
        return this.baseMapper.findByNo(materialCode, vendorCode, werks);
    }

    /**
     * 将过期的配额数据移至配额历史记录表中
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean moveHistoryRecords() {
        //查询已过期配额数据
        List<QuotaEntity> quotaEntityList = quotaDao.selectList(new EntityWrapper<QuotaEntity>().lt("end_date",
                DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA).format(LocalDate.now())));
        //查询数据不空，则移动数据
        if (!CollectionUtils.isEmpty(quotaEntityList)) {
            List<QuotaHistoryEntity> quotaHistoryEntityList = new ArrayList<>();
            //将配额entity数据转换到配额历史记录entity
            quotaEntityList.forEach(item -> {
                QuotaHistoryEntity historyEntity = new QuotaHistoryEntity();
                BeanUtils.copyProperties(item, historyEntity);
                historyEntity.setQuotaId(null);
                quotaHistoryEntityList.add(historyEntity);
                //清空过期的数据
                item.setStartDate(null);
                item.setEndDate(null);
                item.setQuotaNum(BigDecimal.ZERO);
                item.setPercentile(BigDecimal.ZERO);
                item.setUsedQuotaNum(BigDecimal.ZERO);
            });
            quotaHistoryService.insertBatch(quotaHistoryEntityList);
            //更新已过期配额数据
            this.updateAllColumnBatchById(quotaEntityList, quotaEntityList.size());
        }
        return true;
    }

    /**
     * 配额数据模板导入
     *
     * @param file
     * @param username
     */
    @Override
    public Map<String, Object> importQuotaData(File file, String username) {
        ExcelReader reader = ExcelUtil.getReader(file);
        //读取所有数据
        List<List<Object>> allList = reader.read();

        //保存转换后的数据
        List<QuotaEntity> quotaList = new ArrayList<>();
        //记录导入数据行数
        int sum = 0;
        //记录不存在的物料代码、供应商代码
        List<String> materialList = new ArrayList<>();
        List<String> vendorList = new ArrayList<>();
        //返回数据
        Map<String, Object> resultMap = new HashMap<>(3);

        //转换数据至entityList中
        for (int i = 1; i < allList.size(); i++) {
            String materialCode = String.valueOf(allList.get(i).get(0));
            String vendorCode = String.valueOf(allList.get(i).get(1));
            String werks = String.valueOf(allList.get(i).get(2));
            String quotaNum = String.valueOf(allList.get(i).get(3));
            Date startDate = (Date) allList.get(i).get(4);
            Date endDate = (Date) allList.get(i).get(5);
            //判断物料代码存不存在
            MaterialEntity materialEntity = materialService.selectMaterialByCode(materialCode);
            if (materialEntity == null) {
                //保存不存在的物料代码
                materialList.add(materialCode);
                continue;
            }
            //判断供应商存不存在
            VendorInfoEntity vendorInfoEntity = vendorService.selectByVendorCode(vendorCode);
            if (vendorInfoEntity == null) {
                //保存不存在的供应商代码
                vendorList.add(vendorCode);
                continue;
            }
            //根据vendorCode、materialCode查询是否存在,相同vendorCode、materialCode已存在的记录end_date要小于新增记录的开始时间
            List<QuotaEntity> queryList = this.selectList(new EntityWrapper<QuotaEntity>()
                    .eq("vendor_code", vendorCode)
                    .eq("material_code", materialCode)
                    .eq("werks", werks));

            //数据库中是否存在未过期记录
            boolean flag = false;
            for (int j = 0; j < queryList.size(); j++) {
                //数据库中查到的数据开始时间是空，则删除该记录
                if (queryList.get(j).getStartDate() == null) {
                    this.deleteById(queryList.get(j).getQuotaId());
                } else {
                    //数据库中的配额数据开始时间不空，表示未过期，则不允许插入
                    flag = true;
                }
            }
            if (flag) {
                continue;
            }
            QuotaEntity quota = QuotaEntity.builder().materialCode(materialCode).materialDesc(materialEntity.getMaterialDesc())
                    .vendorCode(vendorCode).vendorName(vendorInfoEntity.getVendorName()).werks(werks).creationDate(new Date())
                    .createdBy(username).quotaNum(new BigDecimal(quotaNum)).startDate(startDate).endDate(endDate).build();
            quotaList.add(quota);
            sum++;
        }

        if (quotaList.size() != 0) {
            this.insertBatch(quotaList);
        }

        //返回数据放入map
        resultMap.put("sum", sum);
        resultMap.put("materialList", materialList);
        resultMap.put("vendorList", vendorList);
        return resultMap;
    }
}
